/*!
** @file preferences.js
** @brief Manages the preferences of the user.
** These function can updates the different preferences, and there are all the
** getters to access values. Each getter is protected by a try {...} catch {...}
** block in order to not print error if the preference isn't defined.
** @author Adrien MOGENET
*/

/*!
** @var settings
** @brief object which allow to manage the different settings.
*/
var settings	= Components.classes["@mozilla.org/preferences-service;1"]
		.getService(Components.interfaces.nsIPrefService);

/*
** Get the branch which is associated to our extension
*/
setings		= settings.getBranch ("extensions.keepmybookmarks.");

/*!
** @var loginManager
** @brief object which manages the Logins and Passwords safely
*/
var loginManager = Components.classes["@mozilla.org/login-manager;1"]
		 .getService(Components.interfaces.nsILoginManager);

/*!
** @var nsLoginInfo
** @brief object which can provide information about an user.
*/
var nsLoginInfo	= new Components.Constructor("@mozilla.org/login-manager/loginInfo;1",
					     Components.interfaces.nsILoginInfo,
					     "init");


// objects that represent login <user, pass>.
var isNewUser	= true;
var oldLogin;
var newLogin;


////////////////////////////////////////////////////////////////////////////////
//
// Setters (Updaters) of the different options
//
////////////////////////////////////////////////////////////////////////////////


/*!
** @brief Save the value (bool) of the @c ExportAtEnd checkbox as an user preference.
** @author Adrien MOGENET
*/
function prefAutoUploadUpdate ()
{
    var checked = document.getElementById ('exportatend').checked;
    settings.setBoolPref ("exportatend", checked);
}

/*!
** @brief Save the value (bool) of the @c NetworkMode checkbox as an user preference.
** @author Adrien MOGENET
*/
function prefNetworkModeUpdate ()
{
    var checked = document.getElementById ('savenetwork').checked;
    settings.setBoolPref ("network.status", checked);
}

/*!
** @brief Check the status (booL) of the @c LocalMode checkbox
** @author Adrien MOGENET
*/
function prefLocalModeUpdate ()
{
    var checked = document.getElementById ('savelocal').checked;
    settings.setBoolPref ("local.status", checked);
}

/*!
** @brief Check the status (bool) of the @c HtmlOutput checkbox
** @author Adrien MOGENET
*/
function prefFaviconUpdate ()
{
    var checked = document.getElementById ('favicon').checked;
    settings.setBoolPref ("output.favicon", checked);
}

/*!
** @brief Save the value (bool) of the @c XMLOutput checkbox as an user preference.
** @author Adrien MOGENET
*/
function prefDescriptionUpdate ()
{
    var checked = document.getElementById ('description').checked;
    settings.setBoolPref ("output.description", checked);
}

/*!
** @brief Save the value (string) of the @c host field as an user preference.
** @author Adrien MOGENET
*/
function prefHostUpdate ()
{
    var str = document.getElementById ('host').value;
    settings.setCharPref ("network.host", str);
}

/*!
** @brief Save the value (string) of the @c user field as an user preference.
*/
function prefUserUpdate ()
{
    var str = document.getElementById ('user').value;
    settings.setCharPref ("network.user", str);
}

/*!
** @brief Save the value (string) of the @c path field.
** @author Adrien MOGENET
*/
function prefPathUpdate ()
{
    var str = document.getElementById ('path').value;
    settings.setCharPref ("network.path", str);
}

/*!
** @brief Save the value (string) of the @c localPath field.
** @author Adrien MOGENET
*/
function prefLocalPathUpdate ()
{
    var str = document.getElementById ('localpath').value;
    settings.setCharPref ("local.path", str);
}

/*!
** @brief Manages the password field.
** @c isNewUser is a global boolean which indicates if the user
** is already logged-in or not. If this boolean == true, we only change his
** current Login Information. Otherwise, we set a new Login Information
** @author Adrien MOGENET
*/
function prefPasswordUpdate ()
{
    var password	= document.getElementById ('pass').value;
    var user		= document.getElementById ('user').value;
    var newLogin	= new nsLoginInfo (APP_URI, null, 'KmbPassword', user, password, 'user', 'pass');

    if (password.length > 0)
    {
	if (isNewUser)
	{
	    try
	    {
		loginManager.addLogin (newLogin);
	    }
	    catch (e) { }
	}
	else
	    loginManager.modifyLogin (oldLogin, newLogin);
    }
}


////////////////////////////////////////////////////////////////////////////////
//
// Getters of the different options
//
////////////////////////////////////////////////////////////////////////////////


/*!
** @brief Get the state of the auto-upload
** @return bool : true if upload when browser closes.
** @author Adrien MOGENET
*/
function prefAutoUploadGet ()
{
    try
    {
	return settings.getBoolPref ("exportatend");
    }
    catch (error) { }
    return true;
}

/*!
** @brief Obtain the state of Network Mode
** @return bool : is Network mode enabled.
** @see function @c modeStatusGet()
** @author Adrien MOGENET
*/
function prefNetworkModeGet ()
{
    try
    {
	return settings.getBoolPref ("network.status");
    }
    catch (error) { }
    return false;
}

/*!
** @brief Obtain the state of Local Mode
** @return bool : is Local mode enabled.
** @see function @c modeStatusGet()
** @author Adrien MOGENET
*/
function prefLocalModeGet ()
{
    try
    {
	return settings.getBoolPref ("local.status");
    }
    catch (error) { }
    return false;
}

/*!
** @brief Get the state of HTML output
** @return bool : is HTML output enabled ?
** @author Adrien MOGENET
*/
function prefFaviconGet ()
{
    try
    {
	return settings.getBoolPref ("output.favicon");
    }
    catch (error) { }
    return false;
}

/*!
** @brief Get the state of XML output
** @return bool : is XML output enabled ?
** @author Adrien MOGENET
*/
function prefDescriptionGet ()
{
    try
    {
	return settings.getBoolPref ("output.description");
    }
    catch (error) { }
    return false;
}

/*!
** @brief Get the username for upload in network mode
** @return string : username
** @author Adrien MOGENET
*/
function prefUserGet ()
{
    try
    {
	return settings.getCharPref ("network.user");
    }
    catch (error) { }
    return "";
}

/*!
** @brief Fill the @c password field.
** Returns the password of user, according to the value stored in
** the Login Manager. If the login is correctly retrieved, we fill the field
** and we set the global var @c isNewUser to false. Otherwise, we do nothing
** and returned string is empty.
** @param string : username
** @return string : password
** @todo Ensure a Firefox 2 compatibility
** @todo Translate error message.
** @author Adrien MOGENET
*/
function prefPasswordGet (username)
{
    var httprealm	= 'KmbPassword';
    var password;

    try
    {
	var logins = loginManager.findLogins ({}, APP_URI, null, httprealm);
	for (var i = 0; i < logins.length; i++)
	{
	    if (logins[i].username == username)
	    {
		password	= logins[i].password;
		isNewUser	= false;
		oldLogin	= new nsLoginInfo(APP_URI, null, httprealm, username, password, 'user', 'pass');
		return password;
	    }
	}
    }
    catch (error)
    {
	if (DEBUG)
	    alert ('Error while retrieving the password :\n\n' + error);
    }
    return "";
}

/*!
** @brief Get the path for upload in network mode
** @return string : path (ie : /dir/)
** @todo Let the user select the name of the file ?
** @author Adrien MOGENET
*/
function prefPathGet ()
{
    try
    {
	return settings.getCharPref ("network.path");
    }
    catch (error) { }
    return "/";
}

/*!
** @brief Get the local path for copy in local mode
** @return string : path (ie : /home/me/dir)
** @author Adrien MOGENET
*/
function prefLocalPathGet ()
{
    try
    {
	return settings.getCharPref ("local.path");
    }
    catch (error) { }
    return ".";
}

/*!
** @brief Get the host for upload in network mode
** @return string : host (ie : ftp.server.com)
** @author Adrien MOGENET
*/
function prefHostGet ()
{
    try
    {
	return settings.getCharPref ("network.host");
    }
    catch (error) { }
    return "";
}

/*!
** @brief Get the scheme for upload in network mode (ftp, http...)
** @return string : scheme
** @see file @c default/preferences/keepmybookmarks.js, : default  value is set
** @author Adrien MOGENET
*/
function prefSchemeGet ()
{
    try
    {
	return settings.getCharPref ("network.protocol");
    }
    catch (error) {}
    return "ftp";
}


////////////////////////////////////////////////////////////////////////////////
//
// Main functions, to save and restore the preferences
//
////////////////////////////////////////////////////////////////////////////////


/*!
** @brief Save the preferences
** @see function @c appValidate()
** @author Adrien MOGENET
*/
function savePreferences ()
{
    prefAutoUploadUpdate ();
    prefNetworkModeUpdate ();
    prefLocalModeUpdate ();
    prefFaviconUpdate ();
    prefDescriptionUpdate ();
    prefUserUpdate ();
    prefPasswordUpdate ();
    prefHostUpdate ();
    prefPathUpdate ();
    prefLocalPathUpdate ();

    if (DEBUG)
	alert ('Settings saved !');
}

/*!
** @brief Retrieves the preferences
** @todo var @c networkmode_protocol is currently unused...
** @see function @c appLoad()
** @author Adrien MOGENET
*/
function retrievePreferences ()
{
    var networkmode_protocol				= prefSchemeGet ();
    var networkmode_path				= prefPathGet ();
    document.getElementById ('exportatend').checked	= prefAutoUploadGet ();
    document.getElementById ('savenetwork').checked	= prefNetworkModeGet ();
    document.getElementById ('savelocal').checked	= prefLocalModeGet ();
    document.getElementById ('favicon').checked		= prefFaviconGet ();
    document.getElementById ('description').checked	= prefDescriptionGet ();
    document.getElementById ('user').value		= prefUserGet ();
    document.getElementById ('pass').value		= prefPasswordGet (prefUserGet ());
    document.getElementById ('path').value		= prefPathGet ();
    document.getElementById ('host').value		= prefHostGet ();;
    document.getElementById ('localpath').value		= prefLocalPathGet ();
}
